<template>
	<Modal v-model="modalValue" title="新增" width="500" @on-cancel="modalCancel">
		<Row>
			<Col span="20" offset="1">
				<Form ref="addForm" :model="form" :rules="rules" :label-width="100">
					<FormItem label="卡片名称" prop="name">
						<Input clearable  placeholder="请输入卡片名称" v-model="form.name"></Input>
					</FormItem>
					<FormItem label="卡片id" prop="code">
						<Input clearable  placeholder="请输入卡片id" v-model="form.code"></Input>
					</FormItem>
				</Form>
			</Col>
		</Row>
		<div slot="footer">
			<Button @click="modalCancel">取消</Button>
			<Button type="primary" @click="modalConfirm">确认</Button>
		</div>
	</Modal>
</template>

<script>
	import { apiAdd, apiEdit, apiDetail } from '@/api/drug-welfare/card'
	import _ from 'lodash'
	export default {
		name: 'add-card',
		props: {
			value: {
				type: Boolean,
				default: false,
			},
			isEdit: {
				type: Boolean,
				default: false,
			},
			id: {
				type: [String, Number],
				default: '',
			},
		},
		data() {
			return {
				form: {
					name: '',
					code: '',
				},
				rules: {
					name: [{ required: true, message: '卡片名称不能为空', trigger: 'blur' }],
					code: [{ required: true, message: '卡片id不能为空', trigger: 'blur' }],
				},
			}
		},
		methods: {
			// 获取详情
			getDetail() {
				apiDetail({ id: this.id }).then(res => {
					const { name, code, remark, type, status, promote_amount } = res.data.lists
					this.form.name = name
					this.form.code = code
				})
			},
			// 提交
			modalConfirm() {
				this.$refs['addForm'].validate(valid => {
					if (valid) {
						if (this.isEdit) {
							let opt = _.cloneDeep(this.form)
							opt.id = this.id
							apiEdit({ ...opt }).then(res => {
								this.$Message.success('编辑成功')
								this.$emit('on-success')
								this.modalCancel()
							})
						} else {
							apiAdd({ ...this.form }).then(res => {
								this.$Message.success('新增成功')
								this.$emit('on-success')
								this.modalCancel()
							})
						}
					}
				})
			},
			modalCancel() {
				this.$refs['addForm'].resetFields()
				this.$nextTick(() => {
					this.modalValue = false
				})
			},
		},
		computed: {
			modalValue: {
				get() {
					return this.value
				},
				set(val) {
					this.$emit('input', val)
				},
			},
		},
		watch: {
			value(val) {
				if (val && this.isEdit) {
					this.getDetail()
				}
			},
		},
		mounted() {},
	}
</script>

<style scoped lang="less"></style>
